﻿using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using socketAssist.Handler;
using socketAssist.Procol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace socketAssist
{
    public class DotNettyClient
    {
        public Func<String> OnRecievedFun { get; set; }
        public async Task<IChannel> start(String ip,int port)
        {
            var group = new MultithreadEventLoopGroup();
            var bootstrap = new Bootstrap();
            bootstrap
                .Group(group)
                .Channel<TcpSocketChannel>()
                .Option(ChannelOption.TcpNodelay, true)
                .Handler(
                    new ActionChannelInitializer<ISocketChannel>(
                        channel =>
                        {
                            IChannelPipeline pipeline = channel.Pipeline;
                            pipeline.AddLast("framing-enc", new MyProcolEncoder());
                            pipeline.AddLast("framing-dec", new MyProcolDecoder());
                            var clientHandler = new ClientHandler();
                            clientHandler.OnRecievied += OnRecievedAction;
                            pipeline.AddLast("echo", clientHandler);

                        }));

            return await bootstrap.ConnectAsync(ip,port);
        }

        private void OnRecievedAction(string obj)
        {
            //OnRecievedFun()
        }
    }
}
